<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;
use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 金山2019
 */
class Jinshan2019Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $ismobile = isMobile();

        $data = array();
        $data['merchant_no'] = $this->config['mch_id'];
        $data['nonce_str'] = md5(date("Y-m-d H:i:s",time()) . mt_rand(10000,99999));
        $data['request_no'] = $return['orderid'];
        $data['amount'] = $return['amount'];

        switch($product['paytype']){
            case 1:
                $data['pay_channel'] = 'WXP';
                break;
            //支付宝扫码
            //支付宝H5
            case 3:
			case 4:
            case 17:
            case 18:
				if($ismobile){
					//$data['pay_channel'] = 'ALH5';
                    $data['pay_channel'] = 'ALP';
				}else{
					$data['pay_channel'] = 'ALP';
				}
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);

        }
        $data['request_time'] = time();
        //$data['account_type'] = 1;
        $data['notify_url'] = $return['notifyurl'];
        $data['goods_name'] = 'zf';
        $data['ip_addr'] = getIP();
        $data['return_url'] = $return['callbackurl'];


        ksort($data);
        $str = arrToUrlStr($data)."&key=".$this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));
        $apiurl = $this->config['gateway'];

        $res = curl($apiurl, arrToUrlStr($data));

        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res]);

        $res_arr = json_decode($res, true);

        $qrcode = $res_arr['data']['bank_url'];

        if(!$qrcode){
            if($res_arr['data']['message']){
                $this->showmessage($res_arr['data']['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取二维码失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		
		//echo $qrcode;exit;

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $qrcode);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=".base64_encode($qrcode));

        switch($this->config['paytype']){
            //微信
            case 1:
                header("Location:{$qrcode}"); exit;
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                if($ismobile){
                    header("Location:{$qrcode}"); exit;
                    $this->display("WeiXin/alipaywap");
                }else{
                    header("Location:{$qrcode}"); exit;
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
		//$this->debug_callback();

        $p = file_get_contents('php://input');

        if(!$this->checkip(getIP(),['39.109.9.31','39.109.11.204','39.109.11.171'])){
            exit("wrong");
        }
        
		//$p = '{"success":true,"data":{"status":"3","request_no":"2019011218333964012","request_time":"1547289219","order_no":"JSP12BDC329A723F85A16756B4A19922","pay_time":"1547289232","amount":"50","merchant_no":"JSP1800830","pay_channel":"ALH5","body":null,"nonce_str":"5c39c29045073","call_nums":1,"sign":"3A89217F813CA1596F9F9894B70A06CC"}}';

        if(!$p){
            exit("");
        }

        $arr = json_decode($p, true);

        if(empty($arr)){
            exit("");
        }

        //获取订单信息
        $orderid = $arr['data']['request_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($arr['data']['order_no'])
        ));

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);


        if($arr['success'] != 1 || $arr['data']['sign']==''){
            exit("fail");
        }

        if($arr['data']['status'] != 3){
            exit("pay_fail");
        }

        //echo '<pre/>'; print_r($p);
        if(!$p || empty($p)){
            exit("wrong");
        }

        $sign = $arr['data']['sign'];

        $brr = $arr['data'];
        unset($brr['sign']);
		
		//echo '<pre/>'; print_r($brr);

        ksort($brr);
		
		$str = '';
		
		foreach($brr as $k=>$v){
			if($v === '' || $v === NULL){
				continue;
			}
			
			$str .= "{$k}={$v}&";
		}
        $str = $str . "key=".$this->config['signkey'];


        $sign2 = strtoupper(md5($str));
		
		//echo 'sign: '.$sign.'<br/>';
		//echo 'sign2: '. $sign2; exit;
		
        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }
		
        $this->async($find['pay_orderid'],'SUCCESS');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}